<?php
class SaleModel extends TransModel {
	protected $_validate = array(
		array('customer_id','require','必须选择客户！'), //默认情况下用正则进行验证
		array('sale_no','','单号已经存在，请输入不同单号或在原单号中进行补录！',0,'unique',1), 
	);

	protected $_auto = array(
        array('create_time','intime',1,'callback'),
        array('update_time','time',2,'function'),
        array('sale_no','getmano',1,'callback'),
    );

    /*
     *拆分订单:不同仓库的商品,将按仓库拆分成不同的订单
     *@sale_id 订单ID
     *@auto 是否是自动拆单,默认为1,表示自动拆单
     */
    public static function split_order($sale_id="",$auto = 1){
        //前提:订单在生成时,对应商品明细内的仓库已经被正确分配
        $sale_detail_model =M('Sale_detail'); 
        $sale_model = M('Sale');
        $count_wid = $sale_detail_model->where('sale_id ='.$sale_id)->count('distinct(warehouse_id)');
        if( $count_wid == 1 ){ //同一仓库的订单,勿需拆单
            $wid = $sale_detail_model->where('sale_id ='.$sale_id)->getField('warehouse_id');
            if($wid != 1 && $auto == 1) //自动拆单情况下,若是非默认仓库,则更新订单的仓库
               M('Sale')->where('id = '.$sale_id)->setField('warehouse_id',$wid); 
            elseif($auto != 1 )//人工拆单
               M('Sale')->where('id = '.$sale_id)->setField('warehouse_id',$wid); 
            return;
        }  

        //stock new sale group info
        $sale_groups = $sale_detail_model->where('sale_id ='.$sale_id)->field('sum(number) as snumber,sum(total) as stotal,warehouse_id')->group('warehouse_id')->findAll();

        $sale_details = $sale_detail_model->where('sale_id ='.$sale_id)->findAll();
        $old_sale = $sale_model->where('id ='.$sale_id)->find();

        foreach($sale_groups as $kg=>$group ){
            if($group['warehouse_id'] == 1 ){ //大眼窝同普仓库
                $new_data = array(
                    'total' => $group['stotal'],
                    'sum_number' => $group['snumber'],
                    'warehouse_id' => 1 ,
                    'should_pay' => $group['stotal']+$old_sale['logifee'], //大眼窝增加运费
                );
                $new_data['real_pay'] = $new_data['should_pay'];
                $new_data['sum_pay'] = $new_data['should_pay']; //默认同一值
                $sale_model->where('id ='.$sale_id)->save($new_data);
                unset($new_data);
                continue; //先拆分大眼窝订单,订单号运费保持不变
            }

            //create other branch order
            $new_sale_id = $sale_model->max('id');
            $branch_sale_data = $old_sale;
            $branch_sale_data['id'] = $new_sale_id+1;
            $branch_sale_data['sale_no']= $old_sale['sale_no']."w".$group['warehouse_id']; //新订单号=原单号+w+仓库编号
            $branch_sale_data['warehouse_id']= $group['warehouse_id']; 
            $branch_sale_data['total']= $group['stotal']; 
            $branch_sale_data['sum_number']= $group['snumber']; 
            $branch_sale_data['logifee']= 0; 
            $branch_sale_data['should_pay']= $branch_sale_data['real_pay'] =$branch_sale_data['sum_pay'] =$group['stotal']; 

            $sale_model->add($branch_sale_data); //create new sale

            //save new sale info to sale_groups array
            $sale_groups[$kg]['sale_id'] = $branch_sale_data['id'];
            $sale_groups[$kg]['sale_no'] = $branch_sale_data['sale_no'];

            //create branch sale_detail
            foreach($sale_details as $k=>$value){
                if($group['warehouse_id'] == $value['warehouse_id'] ){
                    $new_sdata = array(
                        'sale_id' => $branch_sale_data['id'],
                        'sale_no' => $branch_sale_data['sale_no'],
                    );
                    $sale_detail_model->where('id ='.$value['id'])->save($new_sdata);     
                    unset($new_sdata);
                } 
            }
            unset($branch_sale_data);
        }

    }

  /**
  **根据订单号，指定增加赠品 ，包括产品赠品规则及满赠规则
  ** @sale_no 订单数组
  **/
  public static function mass_add_gift($sale_nos =array())
  {
    if(count($sale_nos) < 1 )
      return;
    foreach ($sale_nos as $value) {
        self::auto_add_gift($value);
    }
  }

  //自动 为系统中符合赠品 条件的订单 增加赠品，需要人工触发,也可机器自动执行，最好间隔时间长，这样合并订单绑定赠品准些
  public static function auto_split_mass_order()
  {
      $split_map = array(
        'order_status' => 2, //待发货
        'status' => 0, //待审核的
      );
      $require_split_orders = M('Sale')->where($split_map)->field('id')->findAll();
      foreach ($require_split_orders as $key => $value) {
          self::split_order($value['id']);
          sleep(0.15);
      }
  }

}
?>
